package com.jic.market.impl.rest.discount.processor;

import com.jic.market.common.util.Money;
import com.jic.market.entity.PromotionLimitRuleEntity;
import com.jic.market.entity.PromotionMerchantProductEntity;
import com.jic.market.entity.skill.SkillActivityConfig;
import com.jic.market.entity.skill.SkillActivityTimeConfig;
import com.jic.market.enums.DiscountAmountServiceOperateEnum;
import com.jic.market.impl.rest.discount.model.GoodsDetailModel;
import com.jic.market.mapper.PromotionMerchantProductEntityMapper;
import com.jic.market.mapper.skill.SkillActivityConfigMapper;
import com.jic.market.mapper.skill.SkillActivityTimeConfigMapper;
import com.jic.market.request.rest.discount.DiscountBaseRequest;
import com.jic.market.response.rest.discount.SkillTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * @author yinhaijun
 * @date: 2020/5/13
 */
@Service("SeckillProcessor")
public class SeckillProcessor extends AbstractSingleDiscountProcessor {

    @Autowired
    private SkillActivityTimeConfigMapper skillActivityTimeConfigMapper;
    @Autowired
    private PromotionMerchantProductEntityMapper promotionMerchantProductEntityMapper;
    @Autowired
    private SkillActivityConfigMapper skillActivityConfigMapper;

    @Override
    public SingleResult isCondition(GoodsDetailModel goodsDetailModel, DiscountBaseRequest request, DiscountAmountServiceOperateEnum operate) {
        if(!checkPromotion(request.getThirdUserId(), request.getAdminOperate().getChildId().toString(), goodsDetailModel.getChannelCodes(), goodsDetailModel.getPromotionMemberGradeList())){
            return new SingleResult(false, "秒杀计算"+goodsDetailModel.getPromotionCode()+"会员等级校验未通过");
        }
        PromotionMerchantProductEntity promotionMerchantProductEntity = promotionMerchantProductEntityMapper.queryEntityByPromotionIdAndMpId(Long.parseLong(goodsDetailModel.getPromotionId()), goodsDetailModel.getSkuId());
        // 限购
        PromotionLimitRuleEntity promotionLimitRuleEntity = new PromotionLimitRuleEntity();
        promotionLimitRuleEntity.setChannelIndividualLimit(promotionMerchantProductEntity.getChannelIndividualLimit().longValue());
        promotionLimitRuleEntity.setChannelStoreLimit(promotionMerchantProductEntity.getChannelStoreLimit().longValue());
        LimitRuleResult limitRuleResult = checkCommonLimitRule(promotionLimitRuleEntity, goodsDetailModel.getPromotionId(), goodsDetailModel, goodsDetailModel.getFrontPromotionTypeEnum(), request.getThirdUserId());
        if(!limitRuleResult.getLimitCheck()){
            return new SingleResult(false, "限购未通过");
        }
        BigDecimal skillPrice = promotionMerchantProductEntity.getPromPrice();
        if(!(skillPrice.compareTo(goodsDetailModel.getSalePrice()) == -1 && skillPrice.compareTo(BigDecimal.ZERO) == 1)){
            return new SingleResult(false, "秒杀价格不正确");
        }

        // 秒杀时间段
        List<SkillActivityTimeConfig> skillActivityTimeConfigList =  skillActivityTimeConfigMapper.queryByPromotionId(goodsDetailModel.getPromotionId());
        List<SkillTime> skillTimeList = new ArrayList<>();
        Boolean skillInTime = false;
        for(SkillActivityTimeConfig skillActivityTimeConfig : skillActivityTimeConfigList){
            String startTimeOfDate = skillActivityTimeConfig.getStartTimeOfDate();
            String endTimeOfDate = skillActivityTimeConfig.getEndTimeOfDate();
            SkillTime skillTime = new SkillTime();
            BeanUtils.copyProperties(skillActivityTimeConfig, skillTime);
            skillTimeList.add(skillTime);
            Boolean inTime = inTime(startTimeOfDate, endTimeOfDate);
            skillTime.setInTime(inTime);
            if(inTime){
                skillInTime = true;
            }
        }
        goodsDetailModel.setSkillTimeList(skillTimeList);
        if(!skillInTime){
            return new SingleResult(false, "秒杀时间未到");
        }
        SingleResult singleResult = new SingleResult(true, "秒杀优惠");
        singleResult.setObject(skillPrice);//秒杀价
        return singleResult;
    }

    @Override
    public void queryShoppingCartAfter(SingleResult singleResult, GoodsDetailModel goodsDetailModel, DiscountBaseRequest request) {
        // 优惠总价 = (原价 - 秒杀价)*数量
        BigDecimal single = Money.subtract(goodsDetailModel.getSalePrice(), (BigDecimal) singleResult.getObject());
        BigDecimal promotionDiscountTotalAmount =  Money.multiply(single, new BigDecimal(goodsDetailModel.getSingleValidNum()));
        goodsDetailModel.setPromotionDiscountTotalAmount(promotionDiscountTotalAmount);
        // 超限规则
        SkillActivityConfig skillActivityConfig = skillActivityConfigMapper.queryByPromotionId(goodsDetailModel.getPromotionId());
        if(null != skillActivityConfig){
            goodsDetailModel.setOverLimitRule(skillActivityConfig.getOverLimitRule());
            if("1".equals(skillActivityConfig.getOverLimitRule()) && goodsDetailModel.getNum() > goodsDetailModel.getSingleValidNum()){
                singleResult.setMessage("超限了不可购买");
            }
        }
    }

    @Override
    public void querySettlementAfter(SingleResult singleResult, GoodsDetailModel goodsDetailModel, DiscountBaseRequest request){
        queryShoppingCartAfter(singleResult, goodsDetailModel, request);
    }

    private static Boolean inTime(String startTimeOfDate, String endTimeOfDate){
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//        String now = simpleDateFormat.format(new Date());
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int min = calendar.get(Calendar.MINUTE);
        int senc = calendar.get(Calendar.SECOND);
        int second = hour * 3600 + min * 60 + senc;
        String[] startTimeOfDateStr = startTimeOfDate.split(":");
        Integer startTime1 = Integer.parseInt(startTimeOfDateStr[0])*3600;
        Integer startTime2 = Integer.parseInt(startTimeOfDateStr[1])*60;
        Integer startSecond = startTime1 + startTime2;

        String[] endTimeOfDateStr = endTimeOfDate.split(":");
        Integer endTime1 = Integer.parseInt(endTimeOfDateStr[0])*3600;
        Integer endTime2 = Integer.parseInt(endTimeOfDateStr[1])*60;
        Integer endSecond = endTime1 + endTime2;
        if(second >= startSecond && second <= endSecond){
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    public static void main(String[] args){
        System.out.println(inTime("01:00","2:00"));
    }

}
